#!/usr/bin/env bash

WORK_ROOT=`pwd`
export GOPATH=${WORK_ROOT}
export LD_LIBRARY_PATH="${WORK_ROOT}/third/protobuf-3.2.0/lib/"
export PATH="${WORK_ROOT}/bin:${PATH}"
alias protoc="${WORK_ROOT}/third/protobuf-3.2.0/bin/protoc"
if [[ $(uname -s) == "Linux" ]]; then
    alias echo="echo -e"
fi

function warn() {
    echo "[31m$1[0m"
}

function info() {
    echo "[32m$1[0m"
}

function install_protoc() {
    output=${WORK_ROOT}/third/protobuf-3.2.0
    [[ -e ${output} ]] && info "${output} is exists" && return 0
    mkdir -p third && cd third &&
    wget https://github.com/google/protobuf/releases/download/v3.2.0/protobuf-cpp-3.2.0.tar.gz &&
    tar -xzvf protobuf-cpp-3.2.0.tar.gz && cd protobuf-3.2.0 &&
    ./configure --prefix=${output} && make -j8 && make install &&
    info "install protoc success" && return 0
    warn "install protoc fail" && return 255
}

function install_go_dependency() {
    go get -v -u github.com/golang/protobuf/proto github.com/golang/protobuf/protoc-gen-go &&
    go get -v -u google.golang.org/grpc &&
    go get -v -u gopkg.in/alecthomas/kingpin.v2 &&
    info "install go dependency success" && return 0
    warn "install go dependency fail" && return 255
}

function codegen() {
    cd proto &&
    protoc --go_out=plugins=grpc:. *.proto &&
    mkdir -p ${WORK_ROOT}/src/rta_proto &&
    mv *.go ${WORK_ROOT}/src/rta_proto &&
    info "gencode success" && return 0
    warn "gencode failed" && return 255
}

function build() {
    for f in $(\ls src/main); do
        if [[ ${f} == 'version.go' ]]; then
            continue
        fi
        go build -ldflags "-X 'main.Version=version:  $(git describe --tags) [git describe --tags]
hashcode: $(git rev-parse HEAD) [git rev-parse HEAD]
datetime: $(date '+%Y-%m-%d %H:%M:%S') [date]
hostname: $(hostname) [hostname]'" src/main/${f} src/main/version.go
        if [[ $? != 0 ]]; then
            warn "build src/main/${f} failed." && return 255
        fi
    done
}

function usage() {
    info "usage: "
    info "  sh build.sh <dependency | codegen | build>"
    info "  dependency  安装依赖"
    info "  codegen     生成代码"
    info "  build       编译"
}

function main() {
    case "$1" in
        "dependency") install_protoc && install_go_dependency;;
        "codegen") codegen;;
        "build") build ;;
        *) usage;;
    esac
}

main "$@"
